<template>
  <div class="enhanced-software-selection">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <h1 class="page-title">
            <el-icon><Box /></el-icon>
            软件选择中心
          </h1>
          <p class="page-description">精选优质开发工具，一键构建专属开发环境</p>
        </div>
        
        <div class="stats-section">
          <div class="stat-item">
            <span class="stat-number">{{ statistics.totalSoftware }}</span>
            <span class="stat-label">软件总数</span>
          </div>
          <div class="stat-item">
            <span class="stat-number">{{ statistics.totalCategories }}</span>
            <span class="stat-label">分类数</span>
          </div>
          <div class="stat-item">
            <span class="stat-number">{{ formatDownloadCount(statistics.totalDownloads) }}</span>
            <span class="stat-label">总下载量</span>
          </div>
        </div>
      </div>
    </div>

    <div class="main-content">
      <!-- 左侧筛选面板 -->
      <div class="filter-sidebar">
        <el-card class="filter-card">
          <template #header>
            <div class="filter-header">
              <span>筛选条件</span>
              <el-button type="text" size="small" @click="clearAllFilters">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </div>
          </template>

          <!-- 搜索框 -->
          <div class="filter-section">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索软件名称、描述..."
              clearable
              @input="handleSearch"
              @keyup.enter="handleSearchSubmit"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>

          <!-- 操作系统筛选 -->
          <div class="filter-section">
            <div class="filter-title">操作系统</div>
            <el-radio-group v-model="selectedOs" @change="handleOsChange">
              <el-radio label="windows">
                <el-icon><Monitor /></el-icon>
                Windows
              </el-radio>
              <el-radio label="linux">
                <el-icon><Ubuntu /></el-icon>
                Linux
              </el-radio>
              <el-radio label="macos">
                <el-icon><Apple /></el-icon>
                macOS
              </el-radio>
            </el-radio-group>
          </div>

          <!-- 分类筛选 -->
          <div class="filter-section">
            <div class="filter-title">软件分类</div>
            
            <!-- 热门分类 -->
            <div class="popular-categories" v-if="popularCategories.length">
              <div class="section-subtitle">热门分类</div>
              <div class="category-tags">
                <el-tag
                  v-for="category in popularCategories.slice(0, 6)"
                  :key="category"
                  :type="selectedCategory === category ? 'primary' : ''"
                  :effect="selectedCategory === category ? 'dark' : 'plain'"
                  @click="handleCategorySelect(category)"
                  class="category-tag"
                  size="small"
                >
                  {{ category }}
                </el-tag>
              </div>
            </div>

            <!-- 所有分类 -->
            <div class="all-categories">
              <div class="section-subtitle">所有分类</div>
              <el-select
                v-model="selectedCategory"
                placeholder="选择分类"
                clearable
                @change="handleCategoryChange"
                style="width: 100%"
              >
                <el-option label="全部分类" value="" />
                <el-option
                  v-for="category in categories"
                  :key="category"
                  :label="category"
                  :value="category"
                />
              </el-select>
            </div>
          </div>

          <!-- 已选择的软件 -->
          <div class="filter-section" v-if="selectedCount > 0">
            <div class="filter-title">
              已选择 ({{ selectedCount }})
              <el-button type="text" size="small" @click="clearSelection">
                清空
              </el-button>
            </div>
            <div class="selected-list">
              <el-tag
                v-for="software in selectedSoftwareDetails.slice(0, 5)"
                :key="software.id"
                closable
                @close="deselectSoftware(software.id)"
                size="small"
              >
                {{ software.displayName }}
              </el-tag>
              <div v-if="selectedCount > 5" class="more-count">
                还有 {{ selectedCount - 5 }} 个...
              </div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 右侧内容区域 -->
      <div class="content-area">
        <!-- 工具栏 -->
        <div class="toolbar">
          <div class="toolbar-left">
            <el-button-group>
              <el-button
                :type="viewMode === 'grid' ? 'primary' : ''"
                @click="viewMode = 'grid'"
                size="small"
              >
                <el-icon><Grid /></el-icon>
                网格
              </el-button>
              <el-button
                :type="viewMode === 'list' ? 'primary' : ''"
                @click="viewMode = 'list'"
                size="small"
              >
                <el-icon><List /></el-icon>
                列表
              </el-button>
            </el-button-group>

            <div class="result-info">
              <span v-if="!listLoading">
                共找到 {{ totalCount }} 个软件
              </span>
            </div>
          </div>

          <div class="toolbar-right">
            <!-- 排序选项 -->
            <el-select
              v-model="sortField"
              @change="handleSortChange"
              placeholder="排序方式"
              size="small"
              style="width: 150px"
            >
              <el-option label="推荐排序" value="priority" />
              <el-option label="下载量" value="downloadCount" />
              <el-option label="评分" value="rating" />
              <el-option label="最新" value="createdAt" />
            </el-select>

            <!-- 批量操作 -->
            <el-dropdown @command="handleBatchAction" trigger="click">
              <el-button type="primary" size="small" :disabled="!hasData">
                批量操作
                <el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="selectAll">全选当前页</el-dropdown-item>
                  <el-dropdown-item command="selectNone">取消全选</el-dropdown-item>
                  <el-dropdown-item command="selectCommon" divided>选择常用软件</el-dropdown-item>
                  <el-dropdown-item command="selectDevelopment">开发环境套装</el-dropdown-item>
                  <el-dropdown-item command="selectByCategory">按分类选择</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>

        <!-- 软件列表 -->
        <div class="software-container">
          <!-- 加载状态 -->
          <div v-if="listLoading" class="loading-container">
            <el-skeleton :rows="6" animated />
          </div>

          <!-- 错误状态 -->
          <div v-else-if="error" class="error-container">
            <el-empty
              :image="errorImage"
              description="加载失败"
            >
              <el-button type="primary" @click="retry">重试</el-button>
            </el-empty>
          </div>

          <!-- 空状态 -->
          <div v-else-if="!hasData" class="empty-container">
            <el-empty
              image="/images/empty-software.svg"
              :description="getEmptyDescription()"
            >
              <el-button type="primary" @click="clearAllFilters">清空筛选条件</el-button>
            </el-empty>
          </div>

          <!-- 软件列表 -->
          <div v-else>
            <!-- 网格视图 -->
            <div v-if="viewMode === 'grid'" class="software-grid">
              <enhanced-software-card
                v-for="software in softwareList"
                :key="software.id"
                :software="software"
                :selected="isSelected(software.id)"
                @selection-change="handleSelectionChange"
                @view-detail="handleViewDetail"
                @download="handleDownload"
                @share="handleShare"
                @favorite="handleFavorite"
              />
            </div>

            <!-- 列表视图 -->
            <div v-else class="software-list">
              <software-list-item
                v-for="software in softwareList"
                :key="software.id"
                :software="software"
                :selected="isSelected(software.id)"
                @selection-change="handleSelectionChange"
                @view-detail="handleViewDetail"
                @download="handleDownload"
              />
            </div>

            <!-- 分页组件 -->
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :total="totalCount"
                :page-sizes="[12, 24, 48, 96]"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handlePageSizeChange"
                @current-change="handlePageChange"
                background
              />
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 悬浮操作按钮 -->
    <div class="fab-container" v-if="selectedCount > 0">
      <el-badge :value="selectedCount" :max="99" type="primary">
        <el-button
          type="primary"
          size="large"
          round
          @click="handleGenerateScript"
          :loading="scriptGenerating"
        >
          <el-icon><Document /></el-icon>
          生成脚本
        </el-button>
      </el-badge>
    </div>

    <!-- 软件详情弹窗 -->
    <software-detail-dialog
      v-model="detailDialogVisible"
      :software-id="selectedSoftwareId"
      @select="handleDialogSelect"
    />
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useSoftwareStore } from '@/stores/software'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Box, Search, Refresh, Monitor, Ubuntu, Apple, Grid, List,
  ArrowDown, Document
} from '@element-plus/icons-vue'

import EnhancedSoftwareCard from '@/components/software/EnhancedSoftwareCard.vue'
import SoftwareListItem from '@/components/software/SoftwareListItem.vue'
import SoftwareDetailDialog from '@/components/software/SoftwareDetailDialog.vue'

export default {
  name: 'EnhancedSoftwareSelection',
  components: {
    EnhancedSoftwareCard,
    SoftwareListItem,
    SoftwareDetailDialog,
    Box, Search, Refresh, Monitor, Ubuntu, Apple, Grid, List,
    ArrowDown, Document
  },
  setup() {
    const router = useRouter()
    const softwareStore = useSoftwareStore()

    // 响应式状态
    const viewMode = ref('grid') // 'grid' | 'list'
    const sortField = ref('priority')
    const sortOrder = ref('desc')
    const searchKeyword = ref('')
    const selectedCategory = ref('')
    const selectedOs = ref('windows')
    const detailDialogVisible = ref(false)
    const selectedSoftwareId = ref(null)
    const scriptGenerating = ref(false)
    const errorImage = '/images/error.svg'

    // 计算属性
    const {
      softwareList,
      categories,
      popularCategories,
      selectedSoftware,
      selectedCount,
      selectedSoftwareDetails,
      currentPage,
      pageSize,
      totalCount,
      totalPages,
      listLoading,
      error,
      statistics
    } = storeToRefs(softwareStore)

    const hasData = computed(() => softwareList.value.length > 0)

    // 方法
    const initializeData = async () => {
      try {
        await Promise.all([
          softwareStore.fetchSoftwarePage(),
          softwareStore.fetchCategories(),
          softwareStore.fetchStatistics()
        ])
      } catch (error) {
        console.error('初始化数据失败:', error)
      }
    }

    const handleSearch = debounce((keyword) => {
      softwareStore.searchSoftware(keyword)
    }, 500)

    const handleSearchSubmit = () => {
      if (searchKeyword.value.trim()) {
        softwareStore.searchSoftware(searchKeyword.value.trim())
      }
    }

    const handleCategorySelect = (category) => {
      selectedCategory.value = selectedCategory.value === category ? '' : category
      softwareStore.setCategoryFilter(selectedCategory.value)
    }

    const handleCategoryChange = (category) => {
      softwareStore.setCategoryFilter(category)
    }

    const handleOsChange = (os) => {
      softwareStore.setOsFilter(os)
    }

    const handleSortChange = (field) => {
      // 这里可以添加排序逻辑
      console.log('排序字段改变:', field)
      // 重新获取数据
      softwareStore.fetchSoftwarePage()
    }

    const clearAllFilters = () => {
      searchKeyword.value = ''
      selectedCategory.value = ''
      softwareStore.clearFilters()
    }

    const handleSelectionChange = (softwareId, selected) => {
      softwareStore.toggleSoftwareSelection(softwareId)
    }

    const handleViewDetail = (softwareId) => {
      selectedSoftwareId.value = softwareId
      detailDialogVisible.value = true
    }

    const handleDownload = async (softwareId) => {
      try {
        await softwareStore.recordDownload(softwareId)
        ElMessage.success('下载记录成功')
      } catch (error) {
        console.error('记录下载失败:', error)
      }
    }

    const handleShare = (software) => {
      // 实现分享功能
      if (navigator.share) {
        navigator.share({
          title: software.displayName,
          text: software.description,
          url: window.location.href
        })
      } else {
        // 复制到剪贴板
        navigator.clipboard.writeText(window.location.href)
        ElMessage.success('链接已复制到剪贴板')
      }
    }

    const handleFavorite = (softwareId) => {
      // 实现收藏功能
      ElMessage.info('收藏功能开发中...')
    }

    const handleBatchAction = (command) => {
      switch (command) {
        case 'selectAll':
          softwareStore.selectAllCurrentPage()
          break
        case 'selectNone':
          softwareStore.deselectAll()
          break
        case 'selectCommon':
          selectCommonSoftware()
          break
        case 'selectDevelopment':
          selectDevelopmentSuite()
          break
        case 'selectByCategory':
          showCategorySelectDialog()
          break
      }
    }

    const selectCommonSoftware = () => {
      const commonSoftware = ['Git', 'Visual Studio Code', 'Node.js', 'Java']
      const commonIds = softwareList.value
        .filter(s => commonSoftware.some(name => s.name.includes(name)))
        .map(s => s.id)
      softwareStore.selectSoftware(commonIds)
    }

    const selectDevelopmentSuite = () => {
      const devCategories = ['IDE', '编程语言', '版本控制', '数据库']
      const devIds = softwareList.value
        .filter(s => devCategories.includes(s.category))
        .map(s => s.id)
      softwareStore.selectSoftware(devIds)
    }

    const showCategorySelectDialog = async () => {
      try {
        const { value: selectedCategories } = await ElMessageBox.prompt(
          '请选择要批量选择的分类（用逗号分隔）',
          '按分类选择',
          {
            inputValue: '',
            inputPlaceholder: '例如：IDE,编程语言'
          }
        )

        if (selectedCategories) {
          const categoryList = selectedCategories.split(',').map(c => c.trim())
          const categoryIds = softwareList.value
            .filter(s => categoryList.includes(s.category))
            .map(s => s.id)
          softwareStore.selectSoftware(categoryIds)
        }
      } catch {
        // 用户取消
      }
    }

    const clearSelection = () => {
      softwareStore.deselectAll()
    }

    const handlePageChange = (page) => {
      softwareStore.changePage(page)
    }

    const handlePageSizeChange = (size) => {
      softwareStore.changePageSize(size)
    }

    const handleGenerateScript = () => {
      if (selectedCount.value === 0) {
        ElMessage.warning('请先选择要安装的软件')
        return
      }
      router.push('/script-generation')
    }

    const handleDialogSelect = (softwareId) => {
      softwareStore.toggleSoftwareSelection(softwareId)
    }

    const isSelected = (softwareId) => {
      return selectedSoftware.value.includes(softwareId)
    }

    const retry = () => {
      softwareStore.clearError()
      initializeData()
    }

    const getEmptyDescription = () => {
      if (searchKeyword.value) {
        return `没有找到包含"${searchKeyword.value}"的软件`
      }
      if (selectedCategory.value) {
        return `分类"${selectedCategory.value}"下暂无软件`
      }
      return '暂无软件数据'
    }

    const formatDownloadCount = (count) => {
      if (!count) return '0'
      if (count < 1000) return count.toString()
      if (count < 1000000) return (count / 1000).toFixed(1) + 'K'
      return (count / 1000000).toFixed(1) + 'M'
    }

    // 防抖函数
    function debounce(func, wait) {
      let timeout
      return function executedFunction(...args) {
        const later = () => {
          clearTimeout(timeout)
          func(...args)
        }
        clearTimeout(timeout)
        timeout = setTimeout(later, wait)
      }
    }

    // 监听器
    watch(() => softwareStore.searchKeyword, (newVal) => {
      searchKeyword.value = newVal
    }, { immediate: true })

    watch(() => softwareStore.selectedCategory, (newVal) => {
      selectedCategory.value = newVal
    }, { immediate: true })

    watch(() => softwareStore.selectedOs, (newVal) => {
      selectedOs.value = newVal
    }, { immediate: true })

    // 生命周期
    onMounted(() => {
      initializeData()
    })

    return {
      // 响应式状态
      viewMode,
      sortField,
      sortOrder,
      searchKeyword,
      selectedCategory,
      selectedOs,
      detailDialogVisible,
      selectedSoftwareId,
      scriptGenerating,
      errorImage,

      // store状态
      softwareList,
      categories,
      popularCategories,
      selectedSoftware,
      selectedCount,
      selectedSoftwareDetails,
      currentPage,
      pageSize,
      totalCount,
      totalPages,
      listLoading,
      error,
      statistics,

      // 计算属性
      hasData,

      // 方法
      handleSearch,
      handleSearchSubmit,
      handleCategorySelect,
      handleCategoryChange,
      handleOsChange,
      handleSortChange,
      clearAllFilters,
      handleSelectionChange,
      handleViewDetail,
      handleDownload,
      handleShare,
      handleFavorite,
      handleBatchAction,
      clearSelection,
      handlePageChange,
      handlePageSizeChange,
      handleGenerateScript,
      handleDialogSelect,
      isSelected,
      retry,
      getEmptyDescription,
      formatDownloadCount
    }
  }
}
</script>

<style lang="scss" scoped>
.enhanced-software-selection {
  min-height: 100vh;
  background: #f8fafc;

  .page-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 32px 24px;

    .header-content {
      max-width: 1200px;
      margin: 0 auto;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .title-section {
        .page-title {
          display: flex;
          align-items: center;
          gap: 12px;
          font-size: 32px;
          font-weight: 700;
          margin: 0 0 8px 0;
        }

        .page-description {
          font-size: 16px;
          margin: 0;
          opacity: 0.9;
        }
      }

      .stats-section {
        display: flex;
        gap: 24px;

        .stat-item {
          text-align: center;

          .stat-number {
            display: block;
            font-size: 24px;
            font-weight: 700;
          }

          .stat-label {
            display: block;
            font-size: 12px;
            opacity: 0.8;
            margin-top: 4px;
          }
        }
      }
    }
  }

  .main-content {
    max-width: 1200px;
    margin: 0 auto;
    padding: 24px;
    display: flex;
    gap: 24px;

    .filter-sidebar {
      width: 280px;
      flex-shrink: 0;

      .filter-card {
        position: sticky;
        top: 24px;

        .filter-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-weight: 600;
        }

        .filter-section {
          margin-bottom: 24px;

          &:last-child {
            margin-bottom: 0;
          }

          .filter-title {
            font-weight: 600;
            margin-bottom: 12px;
            color: #303133;
          }

          .section-subtitle {
            font-size: 12px;
            color: #909399;
            margin-bottom: 8px;
          }

          .category-tags {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin-bottom: 16px;

            .category-tag {
              cursor: pointer;
              transition: all 0.2s;

              &:hover {
                transform: translateY(-1px);
              }
            }
          }

          .selected-list {
            display: flex;
            flex-direction: column;
            gap: 6px;

            .more-count {
              font-size: 12px;
              color: #909399;
              text-align: center;
              padding: 4px;
              background: #f5f7fa;
              border-radius: 4px;
            }
          }

          :deep(.el-radio-group) {
            display: flex;
            flex-direction: column;
            gap: 8px;

            .el-radio {
              margin-right: 0;
              
              .el-radio__label {
                display: flex;
                align-items: center;
                gap: 6px;
              }
            }
          }
        }
      }
    }

    .content-area {
      flex: 1;
      min-width: 0;

      .toolbar {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 24px;
        padding: 16px;
        background: white;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

        .toolbar-left {
          display: flex;
          align-items: center;
          gap: 16px;

          .result-info {
            color: #606266;
            font-size: 14px;
          }
        }

        .toolbar-right {
          display: flex;
          align-items: center;
          gap: 12px;
        }
      }

      .software-container {
        .loading-container,
        .error-container,
        .empty-container {
          background: white;
          border-radius: 8px;
          padding: 48px;
          text-align: center;
        }

        .software-grid {
          display: grid;
          grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
          gap: 24px;
          margin-bottom: 32px;
        }

        .software-list {
          background: white;
          border-radius: 8px;
          overflow: hidden;
          margin-bottom: 32px;
        }

        .pagination-container {
          display: flex;
          justify-content: center;
          padding: 24px;
          background: white;
          border-radius: 8px;
        }
      }
    }
  }

  .fab-container {
    position: fixed;
    bottom: 32px;
    right: 32px;
    z-index: 1000;
  }
}

// 响应式适配
@media (max-width: 1024px) {
  .enhanced-software-selection {
    .page-header .header-content {
      flex-direction: column;
      gap: 24px;
      text-align: center;

      .stats-section {
        justify-content: center;
      }
    }

    .main-content {
      flex-direction: column;
      padding: 16px;

      .filter-sidebar {
        width: 100%;

        .filter-card {
          position: static;
        }
      }

      .content-area .software-container .software-grid {
        grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
        gap: 16px;
      }
    }
  }
}

@media (max-width: 768px) {
  .enhanced-software-selection {
    .page-header {
      padding: 24px 16px;

      .header-content .title-section .page-title {
        font-size: 24px;
      }
    }

    .main-content .content-area {
      .toolbar {
        flex-direction: column;
        gap: 16px;
        
        .toolbar-left,
        .toolbar-right {
          width: 100%;
          justify-content: center;
        }
      }

      .software-container .software-grid {
        grid-template-columns: 1fr;
      }
    }

    .fab-container {
      bottom: 16px;
      right: 16px;
    }
  }
}
</style>
